package com.zteqhd.plugins;

import android.util.Log;

import org.apache.cordova.CallbackContext;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by jiachengwang on 2017/7/11.
 */


public class zteQhdHttpService {

    private static final MediaType FILEMEDIATYPE = MediaType.parse("multipart/form-data");

    private static RequestBody assemblyParams(Map<String,Object> params){

        Set<String> paramsKey=params.keySet();
        MultipartBody.Builder multipartBodyBuilder=new MultipartBody.Builder().setType(MultipartBody.FORM);

        Iterator<String> setpkey=paramsKey.iterator();

        while(setpkey.hasNext()){
            String key=setpkey.next();
            if(params.get(key) instanceof File){

                File parfile=(File)params.get(key);
                multipartBodyBuilder.addFormDataPart(key, parfile.getName(),
                        RequestBody.create(FILEMEDIATYPE, parfile));

            }else{

                multipartBodyBuilder.addFormDataPart(key,(String)params.get(key));
            }

        }

        return multipartBodyBuilder.build();
    }


    public static void uploadFile(String url,Map<String,Object> params,CallbackContext callbackContext) throws IOException {

        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = assemblyParams(params);

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Response response = client.newCall(request).execute();

        if (response.isSuccessful()){

        }else{

        }

    }

}
